package com.ssm.th.controller;

import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * @author: Hsiao
 * @date: 2023-11-23
 * @description:
 */
@Controller
@RequestMapping("/share")
public class ModelController {

    /**
     * 通过Servlet向Request域中写入共享数据
     * @param request
     * @return
     */
    @RequestMapping("/request")
    public String request(HttpServletRequest request) {
        request.setAttribute("data", "Hello ServletRequest");
        return "home";
    }

    /**
     * 通过Servlet向Session域中写入共享数据
     * @param session
     * @return
     */
    @RequestMapping("/session")
    public String session(HttpSession session) {
        session.setAttribute("data", "Hello ServletSession");
        return "home";
    }


    /**
     * 通过Servlet向Application域中写入共享数据
     * @param session
     * @return
     */
    @RequestMapping("/context")
    public String application(HttpSession session) {
        ServletContext context = session.getServletContext();
        context.setAttribute("data", "Hello ServletContext");
        return "home";
    }




    /**
     * 通过ModelAndView向Request域中写入共享数据
     * @return
     */
    @RequestMapping("/mav")
    public ModelAndView modelAndView() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("data", "Hello ModelAndView");
        modelAndView.setViewName("home");
        return modelAndView;
    }

    /**
     * 通过Model向Request域中写入共享数据
     * @param model
     * @return
     */
    @RequestMapping("/model")
    public String model(Model model) {
        model.addAttribute("data", "Hello Model");
        return "home";
    }

    /**
     * 通过Map向Request域中写入共享数据
     * @param map
     * @return
     */
    @RequestMapping("/map")
    public String model(Map<String, Object> map) {
        map.put("data", "Hello Map");
        return "home";
    }

    /**
     * 通过ModelMap向Request域中写入共享数据
     * @param modelMap
     * @return
     */
    @RequestMapping("/mm")
    public String modelMap(ModelMap modelMap) {
        modelMap.addAttribute("data", "Hello ModelMap");
        return "home";
    }

}
